/*
 *
 * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 * -Redistribution of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * Redistribution in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in
 * the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of Oracle nor the names of
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any
 * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
 * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
 * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
 * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT
 * OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
 * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT,
 * SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF
 * THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS
 * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or
 * intended for use in the design, construction, operation or
 * maintenance of any nuclear facility.
 */

package client;

import java.io.*;

import javax.net.ssl.*;

import server.RightsHandler;

/**
 * ClientTransceiver is the client side of receiving and transmitting files.
 * 
 * @author Victor
 */
public class ClientTransceiver extends Transceiver {
	private SSLSocket socket;
	private PrintWriter out;
	private BufferedReader in;
	private OutputStream rawOut;

	/**
	 * Attempts to set up a SSLSocket using <b>connection</b>, output and input
	 * streams.
	 * 
	 * @param connection
	 *            is where the connection will be set up and authenticated
	 * @param documentRoot
	 *            is the path to where files will be received and sent from
	 */
	public ClientTransceiver(ClientAuthenticator connection, String documentRoot) {
		super(documentRoot);

		try {
			socket = connection.validateServerConnection();
			if (socket == null) {
				System.out.println("unvalid server");
				System.exit(0);
			}

			rawOut = socket.getOutputStream();
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
					rawOut)));

			/*
			 * Make sure there were no surprises
			 */
			if (out.checkError())
				System.out
						.println("SSLSocketClient: java.io.PrintWriter error");

			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
//		ClientAuthenticator connection = new ClientAuthenticator("nursenurse",
//				"keystore/nursekeystore", "keystore/nursetruststore", "localhost",
//				7777);
		
		ClientAuthenticator connection = new ClientAuthenticator("doctor",
		"keystore/doctorkeystore", "keystore/doctortruststore", "localhost",
		7777);
		
//		ClientAuthenticator connection = new ClientAuthenticator("rootroot",
//		"keystore/rootkeystore", "keystore/roottruststore", "localhost",
//		7777);

		ClientTransceiver transceiver = new ClientTransceiver(connection,
				"client");

		// transceiver.getFileFromServer(path);
		 transceiver.writeFileToServer("create ", "1990-04-07-9999\\heart 2");
//		transceiver.commandThenListen("delete ", "1990-04-07-9999\\heart");
	}

	/**
	 * Stores a file to the server and closes the connection between the server
	 * and client afterwards.
	 * 
	 * @param arg
	 *            is the path of the file relative to the <b>documentRoot</b>.
	 */
	public void writeFileToServer(String command, String arg) {
		try {
			out.println(command + arg);
			out.flush();

			/*
			 * Make sure there were no surprises
			 */
			if (out.checkError()) {
				System.out
						.println("SSLSocketClient: java.io.PrintWriter error");
			}

			int endIndexOfPath = arg.indexOf(' ');
			String path = arg;
			if (endIndexOfPath != -1) {
				path = arg.substring(0, endIndexOfPath);
			}
			sendFromFile(out, rawOut, path + RightsHandler.JOURNAL_FILE_EXTENSION);

			String inputLine = in.readLine();
			while (inputLine != null) {
				System.out.println(inputLine);
				inputLine = in.readLine();
			}

			in.close();
			rawOut.close();
			out.close();
			socket.close();

		} catch (IOException e) {
			System.out.println("journal does not exist or is empty");
			e.printStackTrace();
		}
	}

	public void commandThenListen(String command, String arg) {
		try {
			out.println(command + arg);
			out.flush();

			/*
			 * Make sure there were no surprises
			 */
			if (out.checkError()) {
				System.out
						.println("SSLSocketClient: java.io.PrintWriter error");
			}

			String inputLine;

			if (command.trim().equals("get")) {
				// if the folder with the patient id does not exist, we need to
				// create if first
				File directory = new File(ClientConsole.DOCUMENT_ROOT
						+ File.separator + arg.substring(0, arg.indexOf('\\')));

				if (!directory.exists()) {
					directory.mkdir();
				}
			}

			String path = arg + RightsHandler.JOURNAL_FILE_EXTENSION;

			while ((inputLine = in.readLine()) != null) {
				if (inputLine.startsWith(BEGINNING_OF_FILE)) {
					writeToFile(in, path);
				} else {
					System.out.println(inputLine);
				}
			}

			in.close();
			rawOut.close();
			out.close();
			socket.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}